package backend

import (
	"context"
	"gitee.com/go-caipu-team/go-caipu-plugin-sdk/backend/httpclient"
	"gitee.com/go-caipu-team/go-caipu-plugin-sdk/genproto/pluginv2"
	"net/http"
)

type dataSDKAdapter struct {
	queryDataHandler QueryDataHandler
}

func newDataSDKAdapter(handler QueryDataHandler) *dataSDKAdapter {
	return &dataSDKAdapter{
		queryDataHandler: handler,
	}
}

// withHeaderMiddleware http.header info add httpclient.WithContextualMiddleware
func withHeaderMiddleware(ctx context.Context, headers http.Header) context.Context {
	if len(headers) > 0 {
		ctx = httpclient.WithContextualMiddleware(ctx,
			httpclient.MiddlewareFunc(func(opts httpclient.Options, next http.RoundTripper) http.RoundTripper {
				if !opts.ForwardHTTPHeaders {
					return next
				}
				return httpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
					for k, v := range headers {
						if req.Header.Get(k) == "" {
							for _, vv := range v {
								req.Header.Add(k, vv)
							}
						}
					}
					return next.RoundTrip(req)
				})
			}))
	}
	return ctx
}
func (a *dataSDKAdapter) QueryData(ctx context.Context, req *pluginv2.QueryDataRequest) (*pluginv2.QueryDataResponse, error) {
	ctx = propagateTenantIDIfPresent(ctx)
	parsedRequest := FromProto().QueryDataRequest(req)
	ctx = withHeaderMiddleware(ctx, parsedRequest.GetHTTPHeaders())
	resp, err := a.queryDataHandler.QueryData(ctx, parsedRequest)
	if err != nil {
		return nil, err
	}
	return ToProto().QueryDataResponse(resp)
}
